<?php
namespace app\admin\controller;

use think\Db;
use think\Loader;


class Admin extends Base
{
    public function lst()
    {
        $admin = Db::name('admin')->order('id')->paginate(6);
        $this->assign('admin', $admin);
        return $this->fetch();
    }

    public function add()
    {
        if (request()->isPost()) {
            $data = [
                'adminname' => input('adminname'),
                'adminpwd' => md5(input('adminpwd')),
            ];
            $validate = Loader::validate('admin');
            if ($validate->check($data)) {
                if (Db::name('admin')->insert($data)) {
//                    $this->redirect('index/index/index');
                    return $this->success('添加管理员成功', 'lst');
                } else {
                    return $this->success('添加管理员失败');
                }
            } else {
                return $this->error($validate->getError());
            }
            return;
        }
        return $this->fetch();
    }

    public function del()
    {
        $id = input('id');
        if ($id == 1) {
            return $this->error('初始化管理员不能删除');
        }
        if (db('admin')->delete($id)) {
            return $this->success('删除管理员成功！', 'lst');
        } else {
            return $this->success('删除管理员失败！');
        }
    }

    public function edit()
    {
        if (request()->isPost()) {
            $admininfo = db('admin')->find(input('id'));
            $adminpwd = $admininfo['adminpwd'];
            $data = [
                'id' => input('id'),
                'adminname' => input('adminname'),
                'adminpwd' => input('adminpwd') ? md5(input('adminpwd')) : $adminpwd,
            ];
            $validate = Loader::validate('admin');
            if ($validate->scene('edit')->check($data)) {
//                echo db('admin')->update($data);
//                die;
                if ($db = db('admin')->update($data)) {
                    return $this->success('修改管理员成功', 'lst');
                } else {
                    return $this->success('无任何修改！');
                }
            } else {
                return $this->error($validate->getError());
            }
            return;
        }
        $id = input('id');
        $admin = Db::name('admin')->where('id', $id)->find();
        $this->assign('admin', $admin);
        return $this->fetch();
    }
}